package RCp2;

import java.io.*;
import java.net.*;

public class ServidorThread extends Thread {

    private Socket socket;
    private BufferedReader entrada;
    private PrintWriter saida;

    //Constructor a partires de un socket
    public ServidorThread(Socket socket) throws IOException {
        this.socket = socket;
        //Establecemo-la canle de entrada
        entrada = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //Establecemo-la canle de saida
        saida = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
        
        this.start();
    }

    @Override
    public void run() {
        try {
            //Recibimo-la mensaxe do cliente
            System.out.println("Esperando mensaxe do cliente en " + socket);
            
            String mensaxe = entrada.readLine();
            
            System.out.println("Mensaxe recibido: " + mensaxe);
            //Enviamo-la resposta
            
            saida.println(mensaxe);
            
            //Cerramo-lo socket para libera-la conexion
            
            socket.close();
       
        } catch (Exception e) {
            System.err.println("Erro: " + e.getMessage());
        }
    }
}
